package com.itheima.sensor;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

	public static final String TAG = "SENSOR";

	private SensorManager manager;
	private Sensor sensor;
	private SensorEventListener listener;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		//创建一个SensorManager来获取系统的传感器服务
		manager = (SensorManager) getSystemService(SENSOR_SERVICE); // 获得管理器
		sensor = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); // 获得方向传感器
		listener = new MySensorEventListener(); // 创建监听器
	}

	protected void onResume() {
		super.onResume();
		/**
		 * 最常用的一个方法 注册事件
		  * 参数1 ：SensorEventListener监听器
		  * 参数2 ：Sensor 一个服务可能有多个Sensor实现，此处调用getDefaultSensor获取默认的Sensor
		 * 参数3 ：模式 可选数据变化的刷新频率
		  */
		manager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL); // 注册监听器
	}

	protected void onPause() {
		super.onPause();
		manager.unregisterListener(listener, sensor); // 取消监听器
	}

	private final class MySensorEventListener implements SensorEventListener {
		public void onSensorChanged(SensorEvent event) {
			Log.i(TAG, "x: " + event.values[0] + ", y: " + event.values[1] + ", z: "
					+ event.values[2]); // 打印监听器的数据

			float x = event.values[0];
			float y = event.values[1];
			float z = event.values[2];

			if (Math.abs(x) <= 3.0f && y >= 8.5f && Math.abs(z) <= 5) {
				portrait();
			}

/*			if (Math.abs(x) >= 8.0f && Math.abs(y) <= 3.5f && Math.abs(z) <= 6.0) {
				landscape();
			}
*/			if (x >= 8.0f && Math.abs(y) <= 3.5f && Math.abs(z) <= 6.0) {
				landscape();
			}

		}

		public void onAccuracyChanged(Sensor sensor, int accuracy) {

		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		Log.w(TAG, "onConfigurationChanged");
		super.onConfigurationChanged(newConfig);
	}

	public void landscape() {
		if (getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
			if (android.os.Build.VERSION.SDK_INT >= 9) {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
			}else{
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			}
		}
	}

	public void portrait() {
		if (getResources().getConfiguration().orientation != Configuration.ORIENTATION_PORTRAIT) {
			if (android.os.Build.VERSION.SDK_INT >= 9) {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
			} else {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			}
		}
	}

}